﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Mvc;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.WebUI.Consts;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.Common;
using XRM.Security.WebUI.Models.Report;
using XRM.Security.WebUI.Models.Report.ReportBuilder;

namespace XRM.Security.WebUI.Controllers
{
    [System.Web.Mvc.Authorize( Roles = "Administrator, ReportEditor" )]
    public class ReportController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadReportForm( ReportTypes reportType )
        {
            var model = new CreateReportModel {ReportType = reportType};
            string viewName = null;
            switch (reportType)
            {
                case ReportTypes.UserReport:
                    model.SelectListItems = InfoSystemRepository.GetAllActual().ToSelectedList()
                        .AddFirst(SelectedListHelper.DefaultAllItem);
                    model.CheckBoxItems = new List<ItemCheckBoxModel>
                        {
                                new ItemCheckBoxModel {Code = ((int)UserStatus.Work).ToString(), Label = UserStatus.Work.Description(), IsChecked = true},
                                new ItemCheckBoxModel {Code = ((int)UserStatus.NotWork).ToString(), Label = UserStatus.NotWork.Description()},
                                new ItemCheckBoxModel {Code = ((int)UserStatus.Vacation).ToString(), Label = UserStatus.Vacation.Description()}
                        };
                    viewName = "UserReportForm";
                    break;
                case ReportTypes.ExpireCertReport:
                    viewName = "ExpireCertReportForm";
                    break;
                case ReportTypes.CertReport:
                    model.SelectListItems = IdentityCenterRepository.GetAll().ToSelectedList()
                        .AddFirst( SelectedListHelper.DefaultAllItem );
                    viewName = "CertReportForm";
                    break;
                case ReportTypes.DepartmentByScsiReport:
                    model.CheckBoxItems = SkziKindRepository.GetAll().Actual().AsEnumerable()
                        .Select( s => new ItemCheckBoxModel
                        {
                                Code = s.SkziKindId.ToString(),
                                Label = s.ShortName,
                                IsChecked = true
                        }).OrderBy(s => s.Label).ToList();
                    viewName = "DepartmentReportForm";
                    break;
                case ReportTypes.RequestByWorkKindReport:
                    model.CheckBoxItems = WorkKindRepository.GetAll().Actual().ToCheckBoxItemsList();
                    viewName = "RequestReportForm";
                    break;
                case ReportTypes.OpenRequestReport:
                    model.CheckBoxItems = WorkKindRepository.GetAll().Actual().ToCheckBoxItemsList();
                    model.SelectListItems = DepartmentRepository.GetAll().ToSelectedList().AddFirst(SelectedListHelper.DefaultAllItem);
                    viewName = "OpenRequestReportForm";
                    break;
                case ReportTypes.ScsiReport:
                    viewName = "ScsiReportForm";
                    break;
            }
            if (viewName == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            return PartialView( viewName, model );
        }

        [System.Web.Mvc.HttpPost]
        public ActionResult Create(CreateReportModel model)
        {   
            if (!ModelState.IsValid)
            {
                var error = ModelState.Values.SelectMany(s => s.Errors).First().ErrorMessage;
                return JsonError(error);
            }
            var reportFileId = ReportBuilderFactory.CreateReport(model, DataManager);
            return Json(new {isSuccess = true, url = Url.Action("Download", new {id = reportFileId})});
        }

        public ActionResult Download(string id)
        {
            var filePath = Directory.GetFiles(ReportBuilderBase.GetTempFileFolder()).FirstOrDefault(s => s.Contains(id));

            if (filePath == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            var bytes = System.IO.File.ReadAllBytes(filePath);
            System.IO.File.Delete(filePath);
            var fileName = Path.GetFileName( filePath ).Replace( id, String.Empty );
            return File( bytes, "application/octet-stream", fileName );
        }
    }
}